import * as Immutable from 'seamless-immutable';
import { WorkView } from '../config/workViews';
import * as _ from 'lodash';
import { Action } from 'redux-actions';

export default function (
  state: Immutable.ImmutableArray<any> = Immutable.from([]),
  action: Action<WorkView>
) {
  const { type, payload } = action;
  let existedIdx = payload ? _.findIndex(state, { path: payload.path }) : -1;
  switch (type) {
    case 'ADD_WORK_VIEW':
      if (existedIdx === -1) {
        return state.concat(payload).flatMap((view: WorkView) => view.path === payload.path ? view.set('isActive', true) : view.set('isActive', false));
      }
      return state.flatMap((view: WorkView) => view.path === payload.path ? view.set('isActive', true) : view.set('isActive', false));
    case 'REMOVE_WORK_VIEW':
      return state.flatMap((view: WorkView): WorkView | any[] => view.path === payload.path ? [] : view);
    default:
      break;
  }
  return state;
}
